<script>
import {Role} from './scripts/role.js'
import {Loop} from './scripts/system/Loop.js'
import {Resizer} from './scripts/system/Resizer.js'
import {
  WebGLRenderer,
  NeutralToneMapping,
  ACESFilmicToneMapping,
  // PMREMGenerator,
  Euler,
  OrthographicCamera,
  Scene,
  DirectionalLight,
  SpotLight,
  SpotLightHelper,
  SRGBColorSpace,
  PCFSoftShadowMap,
  Vector3,
  EquirectangularReflectionMapping,
  AmbientLight
} from 'three'
// import {RoomEnvironment} from 'three/examples/jsm/environments/RoomEnvironment.js'
import {RGBELoader} from 'three/examples/jsm/loaders/RGBELoader.js'
// import {getAssetsFile} from "@/util/common.js"

import './scripts/gifjs/gif.js'
import './scripts/ccapture/CCapture.js'

var capturer
var playerRole;
var roleinfo = {
  "enable": true,
  "camRotation": [
    -1.5168211234570872,
    1.3952955544844565,
    1.5159807611098084
  ],
  "rotation": [
    0,
    0,
    0
  ],
  "camFov": 80,
  "scale": [
    1,
    1,
    1
  ],
  "position": [
    0,
    0,
    0
  ],
  "camPosition": [
    0,
    0,
    0
  ],
  "url": "",
  "actionList": "",
  "eulerAngle": [
    0,
    0,
    0
  ],
  "target": [
    0,
    0,
    0
  ]
}
let renderDom = null;
let scene = null;
let glRenderer = null;
let pmremGenerator = null;
let camera = null;
let loop = null;
let resizer = null;
let rotX = 9
let rotY = 8
let rotZ = 19
let captureing = false
export default {
  name: 'AiHumanWebRenderer',
  emits: ['onLoaded'],
  props: {
    scaleX: {
      type: Number,
      default: 1
    },
    url: String,
    actionList: {
      type: Array,
      default: []
    },
    x: {
      type: String,
      default: '0'
    },
    y: {
      type: String,
      default: '0'
    },
    width: {
      type: String,
      default: '640'
    },
    height: {
      type: String,
      default: '1280'
    },
  },
  data() {
    return {};
  },
  components: {},
  created() {

  },
  mounted() {
    renderDom = this.$refs.renderDom
    this.init()

    this.addNpcRole(this.url, this.actionList)


  },
  methods: {
    activeAction(name, callback) {
      playerRole.activeExtraAction(name, callback)
    },
    generatePicture() {
      glRenderer.render(scene, camera)
      let pic = glRenderer.domElement.toDataURL('image/png')
      return pic
    },
    generateGif(name, finishedCallback) {
      // let workerurl = new URL('./scripts/gifjs/', import.meta.url)
      let workerurl = window.location.origin + '/aihuman' + '/aihuman/utils/gif/'

      console.log('workerurl', workerurl.href + '/')
      capturer = new CCapture({
        format: 'gif',
        workersPath: workerurl,
        verbose: false,
        display: false,
        framerate: 30,
        motionBlurFrames: 0,
        quality: 50,
        // format: document.querySelector('input[name="encoder"]:checked').value,
        // workersPath: '../../src/',
        // timeLimit: 10,
        frameLimit: 0,
        autoSaveTime: 0,
        onProgress: function (p) {
          console.log(p * 100) + '%'
        }
      });
      let action = playerRole.getActionByName(name)
      this.activeAction(name, function () {

        captureing = false;
        capturer.stop();
        capturer.save(function (blob) {
          var file = new FileReader();
          file.readAsDataURL(blob);
          file.onload = function () {
            finishedCallback(file.result)
            console.log(file.result)

          }
          // capturer.stop();
          // capturer = null
        })
        loop.start()
      });
      // // setTimeout(function(){
      // //     // capturer.stop()

      // // },action._clip.duration*1000)

      capturer.start()
      captureing = true;
    },
    changeCustume() {
      roleinfo.url = url
      playerRole.setRoleInfo(roleinfo)
      playerRole.loadGl()
    },
    init() {

      scene = new Scene()

      // let directionalLight = new DirectionalLight('white', 3)
      // directionalLight.position.set(0, 2, 1)
      // // let ambientLight = new AmbientLight(0xffffff,10)
      // // directionalLight.target = playerRole.model
      // // directionalLight.lookAt(playerRole.model)
      // scene.add(directionalLight)
      // scene.add(ambientLight)
      let spotLight = new SpotLight(0xffffff, 2);
      spotLight.position.set(0, 2.5, 1);
      spotLight.angle = Math.PI / 6;
      spotLight.penumbra = 1;
      spotLight.decay = 2;
      spotLight.distance = 0;
      spotLight.lookAt(new Vector3(0, 0, 0))

      spotLight.castShadow = true;
      spotLight.shadow.mapSize.width = 1024;
      spotLight.shadow.mapSize.height = 1024;
      spotLight.shadow.camera.near = 1;
      spotLight.shadow.camera.far = 10;
      spotLight.shadow.focus = 1;
      scene.add(spotLight);


      glRenderer = new WebGLRenderer({
        antialias: true, //开启锯齿
        alpha: true
      })
      glRenderer.shadowMap.type = PCFSoftShadowMap
      glRenderer.shadowMap.enabled = true
      glRenderer.setPixelRatio(window.devicePixelRatio * 2);
      glRenderer.toneMapping = NeutralToneMapping
      glRenderer.gammaOutput = true;
      glRenderer.toneMappingExposure = 1;
      glRenderer.localClippingEnabled = true;
      glRenderer.physicallyCorrectLights = true;
      glRenderer.outputColorSpace = SRGBColorSpace;

      // modelview光源
      // pmremGenerator = new PMREMGenerator( glRenderer );
      // pmremGenerator.compileEquirectangularShader();
      // scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture;


      // 正投影相机
      const k = renderDom.clientWidth / renderDom.clientHeight; //canvas画布宽高比
      const s = 2//控制left, right, top, bottom范围大小
      camera = new OrthographicCamera(-s * k, s * k, s, -s, 1, 100);
      camera.position.set(-0.08, 1.32, 3)

      // initialize the pathtracer
      // pathTracer = new WebGLPathTracer( glRenderer );
      // pathTracer.filterGlossyFactor = 0.5;
      // pathTracer.minSamples = 3;
      // pathTracer.renderScale = 1;
      // pathTracer.setScene( scene, camera );
      // pathTracer.updateCamera();
      // pathTracer.enablePathTracing = true;
      // pathTracer.tiles.set( 6, 6 );

      let url = "https://aiimg.huilan.com/";
      let hdrurl = 'innerPages/commonAssets/texture/equirectangular/studio_small_09_1k.hdr';
      new RGBELoader()
        .setPath(url)
        .load(
          hdrurl,
          function (texture) {
            texture.colorSpace = SRGBColorSpace
            texture.mapping = EquirectangularReflectionMapping

            // scene.background = texture
            scene.environment = texture
            scene.environmentRotation = new Euler(rotX / 100 * 360, rotY / 100 * 360, rotZ / 100 * 360)
            // glRenderer.render(scene, camera)
            // pathTracer.updateEnvironment();
            // pathTracer.updateMaterials();
          },
          function () {
          },
          function (error) {
            console.log(error)
          }
        )

      // 创建全局循环
      loop = new Loop(camera, scene, glRenderer)

      loop.start()
      //创建尺寸适配
      resizer = new Resizer(
        renderDom,
        camera,
        glRenderer
      )
    },
    async addNpcRole(url, actionList) {


      roleinfo.url = url
      roleinfo.actionList = actionList

      playerRole = await new Role(
        roleinfo,
        scene,
        camera,
        loop
      )
      await playerRole.init()


      playerRole.isNpc = true;

      glRenderer.setSize(renderDom.clientWidth, renderDom.clientHeight)
      glRenderer.setPixelRatio(1.5)
      glRenderer.setClearAlpha(0)
      renderDom.appendChild(glRenderer.domElement)
      playerRole.chatRenderer = glRenderer;
      let extraCamera = loop.addCameraView({
        left: 0,
        top: '0',
        width: 1,
        height: 1,
        opacity: '0',
        camera: camera,
        renderer: glRenderer,
        onUpdateCamera: function (camera, scene, renderer) {
          if (capturer) {
            capturer.capture(glRenderer.domElement)
          }

        }
      })
      this.$emit('onLoaded', playerRole.roleAnimations)
    }
  }
}

</script>


<template>

  <div :style="'transform:scaleX('+scaleX+');left:'+x+'px;top:'+y+'px;width:'+width+'px;height:'+height+'px'"
       class="renderDom" ref="renderDom">

    <div id="loading" class="center" style="z-index: 9998;background-color: #ffffff00;">
      <img class="center" id="loadingBackImg" style="width: 100%" src=""/>
      <div class="loader center">
        <!-- <img class="center" style="width: 80%;"
        :src="getAssetsFile('aihuman.png')"
        > -->
      </div>
      <div id="progress-loader" class="progress-loader">
        <div id="loadProgress" class="progress"></div>
      </div>
    </div>

  </div>

</template>

<style scoped>
.center {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  text-align: center;
}

.renderDom {
  margin: auto;
  width: 200px;
  height: 500px;
}

.progress-loader {
  top: auto;
  left: 0;
  right: 0;
  bottom: 30px;
  margin: auto;
  position: absolute;
  /* transform: translate(-50%, -50%); */
  width: 80%;
  background: rgb(32 41 58);
  height: 10px;
  border-radius: 7px;
}

.progress {
  width: 1px;
  height: 10px;
  border-radius: 7px;
  background: rgb(63 102 249);
  transition: 0.5s;
  /* animation: loading_44 5s cubic-bezier(.4,1.01,1,1) infinite; */
}
</style>
./scripts/system/Loop.js./scripts/system/Resizer.js
